﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;

namespace Comet
{
    class Extra
    {
        public static Random rand = new Random();
        public static JavaScriptSerializer oSerializer = new JavaScriptSerializer();

        static List<string> bannedIPs = new List<string>();
        static List<string> flagPhrases = new List<string>();

        public static string GenerateChatID
        {
            get
            {
                string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
                var randomstring = "";
                for (var i = 0; i < 6; i++)
                    randomstring += chars[rand.Next(0, chars.Length - 1)];
                return randomstring;
            }
        }

        public static Dictionary<string, string> ParseRawParams(string raw)
        {
            try
            {
                Dictionary<string, string> dict = new Dictionary<string, string>();
                string[] pairs = raw.Split('&');
                foreach (string pair in pairs)
                {
                    string[] pairRaw = pair.Split('=');
                    dict.Add(pairRaw[0], pairRaw.Length > 1 ? pairRaw[1] : "");
                }
                if (dict.Count == 0) return null;
                else return dict;
            }
            catch { return null; }
        }

        public static void ReLoadBanStuff()
        {
            if (!Directory.Exists("c://comet//config//")) Directory.CreateDirectory("c://comet//config//");

            if (!File.Exists("c://comet//config//banned.txt")) File.WriteAllText("c://comet//config//banned.txt", "");
            bannedIPs = new List<string>(File.ReadAllLines("c://comet//config//banned.txt"));

            if (!File.Exists("c://comet//config//phrases.txt")) File.WriteAllText("c://comet//config//phrases.txt", "");
            flagPhrases = new List<string>(File.ReadAllLines("c://comet//config//phrases.txt"));
        }

        static void BanIP(string ip)
        {
            File.AppendAllText("c://comet//config//banned.txt", Environment.NewLine + ip);
            bannedIPs.Add(ip);
        }

        public static bool CheckIP(string ip)
        {
            if (bannedIPs.Contains(ip))
            {
                return true;
            }
            else return false;
        }

        public static bool FlagIP(string message, string ip)
        {
            foreach (string phrase in flagPhrases)
            {
                if (message.Contains(phrase))
                {
                    BanIP(ip.Split(':')[0]);
                    return true;
                }
            }

            return false;
        }

    }
}